package com.hkyp.ss.course.web.config;


import com.hkyp.ss.course.apis.exception.UnacceptableException;
import com.hkyp.ss.course.web.dto.base.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 全局异常处理
 *
 * @author andy
 * @date 2017/6/12 0012 下午 4:27
 */
@ControllerAdvice
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(HttpServletRequest request, Throwable e) {
        log.error("我们遇到了些状况...", e);
        ResultBean resultBean = new ResultBean();

        if(e instanceof UnacceptableException){
            log.info("测试：哈哈哈哈哈哈哈哈哈");
            resultBean.setMsg(e.getLocalizedMessage());
            resultBean.setCode(ResultBean.VALIDATE_ERROR);
            return resultBean;
        }else if(e instanceof MethodArgumentNotValidException){
            resultBean.setMsg(e.toString());
            resultBean.setCode(ResultBean.VALIDATE_ERROR);
            return resultBean;
        }

        resultBean.setMsg(e.toString());
        resultBean.setCode(ResultBean.FAIL);
        return resultBean;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBean<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {

        // 异常信息
        String msg = extractErrorMsg(e.getBindingResult());

        // 返回对象
        ResultBean<Object> resultBean = new ResultBean<>();

        resultBean.setCode(ResultBean.VALIDATE_ERROR);
        resultBean.setMsg(msg);

        return resultBean;
    }

    /**
     * 异常信息
     *
     * @param result
     * @return
     */
    private String extractErrorMsg(BindingResult result) {
        List<FieldError> errors = result.getFieldErrors();

        return errors.stream().map(e -> e.getField()+ ":" + e.getDefaultMessage())
                .reduce((s1, s2) -> s1 + " ; " +s2).orElseGet( ()->"参数非法");
    }

    /**
     * 异常信息  返回单个
     *
     * @param result
     * @return
     */
    private String extractSingleErrorMsg(BindingResult result) {
        List<FieldError> errors = result.getFieldErrors();

        return errors.stream().findFirst().map(e -> e.getField()+ ":" + e.getDefaultMessage())
                .orElseGet( ()->"参数非法");
    }



}
